﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Dynamic;
using System.Data.SqlClient;
using System.Configuration;
using Model;
using Common;
namespace DAL
{
    public class PrizeRecordDAL
    {
        public static int Save(PrizeRecordInfo info)
        {
            string sql = string.Format("insert into [prize_record]([SID],[UserID],[Money],[PrizeType],[Province],[City],[Area],[Lat],[Lng],[Address],[IsAuto],[CreateID],[CreateDate]) values({0},{1},{2},{3},'{4}','{5}','{6}',{7},{8},'{9}',{10},{11},'{12}');select @@identity;update [red_packet] set IsTake=1 where ActiveID={0} and IsTake=0 and UserID={1};", info.SID, info.UserID, info.Money, info.PrizeType, info.Province, info.City, info.Area, info.Lat, info.Lng, info.Address, info.IsAuto, info.CreateID, info.CreateDate);
            return DataConvert.ToInt(CommonDAL.ExecuteScalar(sql));
        }

        public static List<dynamic> FindData(int userid, string begindate, string enddate)
        {
            string filter = " CreateID="+userid;
            if (!string.IsNullOrEmpty(begindate) && !string.IsNullOrEmpty(enddate))
            {
                filter += " and ([prize_record].CreateDate between '" + DataConvert.ToDateTime(begindate).ToString("yyyy-MM-dd 00:00:00") + "' and '" + DataConvert.ToDateTime(enddate).ToString("yyyy-MM-dd 23:59:59") + "' or convert(char(10),CreateDate,120)=convert(char(10),getdate(),120))";
            }
            DataTable dt = CommonDAL.GetDataTable(string.Format("select count(ID) as PrizeCount,sum(Money) as Money,convert(char(10),CreateDate,120) as CreateDate from [prize_record] where {0} group by convert(char(10),CreateDate,120)", filter));
            List<dynamic> list = new List<dynamic>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(Single_Data(row));
            }
            return list;
        }
        public static List<PrizeRecordInfo> FindPage(string keyword, int id, int startindex, int pagesize, string order, string desc, out int count)
        {
            string filter = " and SID="+id;
            if (!string.IsNullOrEmpty(keyword))
            {
                filter += " and [user].NickName like '%" + keyword+"%'";
            }

            DataTable dt = CommonDAL.FindCPage(startindex, pagesize, order, desc, filter, "[prizerecord_page]", out count);
            List<PrizeRecordInfo> list = new List<PrizeRecordInfo>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(All_Data(row));
            }
            return list;
        }
        public static double PrizeMoney(int sid,int userid)
        {
            return DataConvert.ToDouble(CommonDAL.ExecuteScalar(string.Format("select Money from [prize_record] where SID={0} and UserID={1}", sid, userid)))/100;
        }
        public static int PrizeCount(int sid, int userid)
        {
            return DataConvert.ToInt(CommonDAL.ExecuteScalar(string.Format("select Count(id) from [prize_record] where SID={0} and UserID={1}", sid, userid)));
        }
        public static int PrizeCount(int userid)
        {
            return DataConvert.ToInt(CommonDAL.ExecuteScalar(string.Format("select Count(id) from [prize_record] where UserID={0} and DateDiff(dd,createdate,getdate())=0", userid)));
        }
        public static PrizeRecordInfo FindOneByID(int id)
        {
            DataRow dr = CommonDAL.FindOneByID(id, "[prize_record]");
            return Simple_Data(dr);
        }
        public static bool HasRedOver(int activeid)
        {
            DataRow row = CommonDAL.GetDataRow(string.Format("select top 1 * from [red_packet] where ActiveID={0} and UserID>0", activeid));
            if (row == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public static bool HasOutTime(int activeid, int userid)
        {
            DataRow row = CommonDAL.GetDataRow(string.Format("select top 1 * from [red_packet] where ActiveID={0} and IsTake=0 and UserID={1}", activeid, userid));
            if (row == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public static double MyRedPacketMoney(int activeid, int userid)
        {
            return DataConvert.ToDouble(CommonDAL.ExecuteScalar(string.Format("select money from [red_packet] where ActiveID={0} and IsTake=0 and UserID={1}", activeid, userid)));
        }
        public static double RedPacket(int activeid, int userid)
        {
            DataRow row = CommonDAL.GetDataRow(string.Format("select top 1 * from [red_packet] where ActiveID={0} and IsTake=0 and UserID={1}", activeid, userid));
            //如果我已经占了一个，则继续占我的这个，避免我同时占用2个
            if (row == null)
            {
                row = CommonDAL.GetDataRow(string.Format("select top 1 * from [red_packet] where ActiveID={0} and IsTake=0 and DATEDIFF(s,createdate,GETDATE())>1800", activeid));
            }
            if (row != null)
            {
                CommonDAL.ExecuteScalar(string.Format("update [red_packet] set UserID={0},CreateDate=getdate() where id={1}", userid, DataConvert.ToInt(row["ID"])));
                return DataConvert.ToDouble(row["Money"])/100;
            }
            else
            {
                return 0;
            }
        }
        
        private static dynamic Single_Data(DataRow dr)
        {
            dynamic info = new ExpandoObject();
            if (dr != null)
            {
                info.PrizeCount = DataConvert.ToInt(dr["PrizeCount"]);
                info.Money = DataConvert.ToFloat(dr["Money"])/100;
                info.CreateDate = DataConvert.ToDateTime(dr["CreateDate"]);
            }
            return info;
        }
        private static PrizeRecordInfo Simple_Data(DataRow dr)
        {
            PrizeRecordInfo info = new PrizeRecordInfo();
            if (dr != null)
            {
                info.ID = DataConvert.ToInt(dr["ID"]);
                info.SID = DataConvert.ToInt(dr["SID"]);
                info.UserID = DataConvert.ToInt(dr["UserID"]);
                info.Money = DataConvert.ToFloat(dr["Money"]) / 100;
                info.PrizeType = DataConvert.ToInt(dr["PrizeType"]);
                info.Province = DataConvert.ToString(dr["Province"]);
                info.City = DataConvert.ToString(dr["City"]);
                info.Area = DataConvert.ToString(dr["Area"]);
                info.Lat = DataConvert.ToDouble(dr["Lat"]);
                info.Lng = DataConvert.ToDouble(dr["Lng"]);
                info.Address = DataConvert.ToString(dr["Address"]);
                info.IsAuto = DataConvert.ToInt(dr["IsAuto"]);
                info.CreateDate = DataConvert.ToDateTime(dr["CreateDate"]);
            }
            return info;
        }

        private static PrizeRecordInfo All_Data(DataRow dr)
        {
            PrizeRecordInfo info = new PrizeRecordInfo();
            if (dr != null)
            {
                info.ID = DataConvert.ToInt(dr["ID"]);
                info.SID = DataConvert.ToInt(dr["SID"]);
                info.UserID = DataConvert.ToInt(dr["UserID"]);
                info.Money = DataConvert.ToFloat(dr["Money"]) / 100;
                info.PrizeType = DataConvert.ToInt(dr["PrizeType"]);
                info.Province = DataConvert.ToString(dr["Provinces"]);
                info.City = DataConvert.ToString(dr["Citys"]);
                info.Area = DataConvert.ToString(dr["Area"]);
                info.Lat = DataConvert.ToDouble(dr["Lat"]);
                info.Lng = DataConvert.ToDouble(dr["Lng"]);
                info.Address = DataConvert.ToString(dr["Address"]);
                info.IsAuto = DataConvert.ToInt(dr["IsAuto"]);
                info.CreateDate = DataConvert.ToDateTime(dr["CreateDate"]);

                info.NickName = DataConvert.ToString(dr["NickName"]);
                info.HeadImg = DataConvert.ToString(dr["HeadImg"]);
                info.Sex = DataConvert.ToInt(dr["Sex"]);

            }
            return info;
        }


        public static void DecPrizeRecord()
        {

            List<DeductionInfo> deductionlist = DeductionDAL.FindListOfRun();
            List<ActiveInfo> activelist = ActiveDAL.FindListByIDs(string.Join(",",deductionlist.Select(x=>x.ActiveID)));
            foreach (DeductionInfo info in deductionlist)
            {
                int minute = Commons.DateDiff(info.LastEditTime, DateTime.Now, "S");
                int increasecount =(int)(info.AllCount / (info.Hour * 3600) * minute);
                bool ok = false;
                ActiveInfo active = B.Instance<ActiveInfo>(activelist.FirstOrDefault(x => x.ID == info.ActiveID));
                if (increasecount >= (active.Count - active.TakeCount))
                {
                    increasecount = active.Count - active.TakeCount;
                    CommonDAL.UpdateColumnByID(active.ID, "State", 3, "active");
                    DeductionDAL.FinishDeduction(info.ID);
                }
                if (increasecount >= info.AllCount - info.ActualCount)
                {
                    increasecount = info.AllCount - info.ActualCount;
                    DeductionDAL.FinishDeduction(info.ID);
                }
                for (int i = 0; i < increasecount; i++)
                {
                    double prizemoney = 0;
                    prizemoney = PrizeRecordDAL.RedPacket(active.ID, i + 1);

                    prizemoney = prizemoney * 100;
                    PrizeRecordInfo prize = new PrizeRecordInfo()
                    {
                        UserID = i + 1,
                        SID = active.ID,
                        Money = prizemoney,
                        PrizeType = active.PrizeType,
                        Province = "",
                        City = "",
                        Area = "",
                        Lat = 0,
                        Lng = 0,
                        Address = "",
                        CreateID = active.UserID,
                        CreateDate = DateTime.Now
                    };
                    PrizeRecordDAL.Save(prize);
                    ok = ActiveDAL.UpdateTakeMoney(active.ID, prizemoney);
                }
                if (ok)
                {
                    VisitRecordInfo visit = new VisitRecordInfo()
                    {
                        UserID = 0,
                        SID = active.ID,
                        Province = "",
                        City = "",
                        Area = "",
                        Lat = 0,
                        Lng = 0,
                        Address = "",
                        CreateID = active.UserID,
                        FCount = increasecount,
                        Flag = 2,
                        CreateDate = DateTime.Now
                    };
                    DeductionDAL.DecDeduction(info.ID, increasecount);
                    ActiveDAL.IncClickCount(active.ID, increasecount);
                    ActiveDAL.IncShareCount(active.ID, increasecount);
                    VisitRecordDAL.Save(visit);
                }
                
            }


            
        }

    }
}
